name: Build & Deploy

on:
  push:
    branches:
      - '*'
    tags:
      - '*'

jobs:
  build:
    strategy:
      matrix:
        modules: [front, back]
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ vars.DK_USERNAME }}
          password: ${{ secrets.DK_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          file: ${{ matrix.modules }}/docker/Dockerfile
          context: ${{ matrix.modules }}
          push: true
          tags: agylam/${{ matrix.modules }}:${{ github.ref_name }}

  deploy:
    runs-on: ubuntu-latest
    if: ${{ github.ref_name == 'stage'}}
    needs:
      - build
    steps:
      - uses: actions/checkout@v3

      - name: Copy .env to stand
        uses: garygrossgarten/github-action-scp@release
        with:
            local: .env
            remote: ${{ github.ref_name }}/.env
            host: ${{ secrets.SSH_HOST }}
            username: ${{ secrets.SSH_USER }}
            password: ${{ secrets.SSH_PASSWORD }}
            privateKey: ${{ secrets.SSH_KEY }}
            passphrase: ${{ secrets.SSH_KEYPASS }}

      - name: Copy docker-compose.yml to stand
        uses: garygrossgarten/github-action-scp@release
        with:
            local: docker-compose-cicd.yml
            remote: ${{ github.ref_name }}/docker-compose.yml
            host: ${{ secrets.SSH_HOST }}
            username: ${{ secrets.SSH_USER }}
            password: ${{ secrets.SSH_PASSWORD }}
            privateKey: ${{ secrets.SSH_KEY }}
            passphrase: ${{ secrets.SSH_KEYPASS }}

      - name: Restart stand
        uses: appleboy/ssh-action@v0.1.10
        with:
            host: ${{ secrets.SSH_HOST }}
            username: ${{ secrets.SSH_USER }}
            key: ${{ secrets.SSH_KEY }}
            passphrase: ${{ secrets.SSH_KEYPASS }}
            script: |
                cd ${{ github.ref_name }} && sed -i "s/BRANCH=.*/BRANCH=${{ github.ref_name }}/g" .env && docker-compose pull && docker-compose up -d
